﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Practices.EnterpriseLibrary.Data;
using Microsoft.Practices.EnterpriseLibrary.Common.Configuration;
using Microsoft.Practices.EnterpriseLibrary.Data.Configuration;
using System.Data.Common;
using System.Data;
using System.Collections;
using System.Runtime.Serialization.Formatters.Binary;
using System.IO;

namespace AMStudio.Common
{
    internal class LanguageTagDAL
    {
        public LanguageTagDAL()
        {
            //myDataset = new DataSet();
            //Database db = EnterpriseLibraryContainer.Current.GetInstance<Database>("MachineConfig");
            //string sql = "select * from [language$]";
            //DbCommand cmd = db.GetSqlStringCommand(sql);

            //string productsTable = "[language$]";

            //// Retrieve the initial data.
            //db.LoadDataSet(cmd, myDataset, productsTable);

            //// Get the table that will be modified.
            //DataTable dTable = myDataset.Tables[productsTable];
        }

        public bool Add(LanguageItem item)
        {
            Database db = EnterpriseLibraryContainer.Current.GetInstance<Database>("UIDB");
            StringBuilder sb = new StringBuilder();
            sb.Append(
                "insert into language values(@UIName,@ControlName,@Language,@Comments,@Remark)");
            DbCommand cmd = db.GetSqlStringCommand(sb.ToString());    
            
            db.AddInParameter(cmd, "@UIName", DbType.String, item.UIName);
            db.AddInParameter(cmd, "@ControlName", DbType.String, item.ControlName);
            db.AddInParameter(cmd, "@Language", DbType.Binary, SerializeToByteArray(item.Language));//TODO
            db.AddInParameter(cmd, "@Comments", DbType.String, item.Comments);
            db.AddInParameter(cmd, "@Remark", DbType.String, item.Remark);
            return db.ExecuteNonQuery(cmd) > 0 ? true : false;
        }
        
        public bool Update(LanguageItem item)
        {
            Database db = EnterpriseLibraryContainer.Current.GetInstance<Database>("UIDB");
            StringBuilder sb = new StringBuilder();
            sb.Append("update language set ");
            //sb.Append("ControlName=@ControlName,");
            sb.Append("[Language]=@Language,");
            sb.Append("[Comments]=@Comments,");
            sb.Append("[Remark]=@Remark ");
            sb.Append(" where ([UIName]=@UIName AND [ControlName]=@ControlName)");
            DbCommand cmd = db.GetSqlStringCommand(sb.ToString());
            db.AddInParameter(cmd, "@UIName", DbType.String, item.UIName);
            db.AddInParameter(cmd, "@ControlName", DbType.String, item.ControlName);
            db.AddInParameter(cmd, "@Language", DbType.Binary, SerializeToByteArray(item.Language));
            db.AddInParameter(cmd, "@Comments", DbType.String, item.Comments);
            db.AddInParameter(cmd, "@Remark", DbType.String, item.Remark);
            int r = db.ExecuteNonQuery(cmd);
            return r> 0 ? true : false;;
        }

        public bool Delete(string UIName,string ControlName)
        {
            Database db = EnterpriseLibraryContainer.Current.GetInstance<Database>("UIDB");
            StringBuilder sb = new StringBuilder();
            sb.Append("delete from language ");
            sb.Append(" where UIName=@UIName AND ControlName=@ControlName");
            DbCommand cmd = db.GetSqlStringCommand(sb.ToString());
            db.AddInParameter(cmd, "@UIName", DbType.String, UIName);
            db.AddInParameter(cmd, "@ControlName", DbType.String, ControlName);
            return db.ExecuteNonQuery(cmd) > 0 ? true : false;
        }

        /// <summary>
        /// 查询所有信息
        /// </summary>
        /// <returns></returns>
        public Hashtable SelectAllMapper()
        {
            var list = new Dictionary<string,LanguageItem>();
            Database db = EnterpriseLibraryContainer.Current.GetInstance<Database>("UIDB");
            DataAccessor<LanguageItem> myAccessor;
            myAccessor = db.CreateSqlStringAccessor("select * from [language]",
                MapBuilder<LanguageItem>.MapAllProperties().            
                Map(p => p.Language).WithFunc(dataRecord =>
                    {
                        byte[] content = (byte[])dataRecord["Language"];
                        Hashtable ret= DeserializeFromByteArray(content) as Hashtable;
                        if (ret == null)
                            return new Hashtable();
                        return ret;
                    }).
                    Build()
                );
            list = myAccessor.Execute()
                .ToDictionary<LanguageItem,string>
                ((item)=>
                    {
                        return item.UIName.Trim() + "." + item.ControlName.Trim();
                    });

            var resultList=new Hashtable();
            foreach(KeyValuePair<string,LanguageItem> item in list)
            {
                resultList.Add(item.Key,item.Value);
            }
            return resultList;
        }


        private object DeserializeFromByteArray(byte[] content)
        {
            BinaryFormatter bformatter = new BinaryFormatter();
            MemoryStream mem = new MemoryStream();
            mem.Write(content, 0, content.Length);
            mem.Position = 0;
            return bformatter.Deserialize(mem);
        }

        private byte[] SerializeToByteArray(object content)
        {
            BinaryFormatter bformatter = new BinaryFormatter();
            MemoryStream mem = new MemoryStream();
            bformatter.Serialize(mem, content);
            return mem.ToArray();
        }
    }
}
